package com.ruoyi.web.controller.system;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginBodyWithoutCaptcha;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.mapper.SysStudentMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api(tags = "用户登录接口")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;
    
    @Autowired
    private SysStudentMapper sysStudentMapper;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(
        value = "用户登录", 
        notes = "用于系统用户登录认证，需要验证用户名密码正确性及验证码有效性",
        response = AjaxResult.class,
        responseReference = "{\"成功\":{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"token\":\"eyJ0eXAi...\"}},\"失败\":{\"code\":500,\"msg\":\"用户不存在/密码错误/验证码错误等具体错误信息\"}}"
    )
    @ApiImplicitParam(
        name = "loginBody", 
        value = "登录信息", 
        required = true, 
        dataType = "LoginBody",
        example = "{\"username\":\"admin\",\"password\":\"admin123\",\"code\":\"1234\",\"uuid\":\"abc123\"}"
    )
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class, examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":200,\"msg\":\"操作成功\",\"token\":\"eyJhbGciOiJIUzUxMiJ9.xxx\"}")
        })),
        @ApiResponse(code = 500, message = "操作失败")
    })
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    
    @ApiOperation(
        value = "用户登录（无验证码）", 
        notes = "用于系统用户登录认证，仅校验用户名和密码的正确性，不需要验证码",
        response = AjaxResult.class,
        responseReference = "{\"成功\":{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"token\":\"eyJ0eXAi...\"}},\"失败\":{\"code\":500,\"msg\":\"用户不存在/密码错误等具体错误信息\"}}"
    )
    @ApiImplicitParam(
        name = "loginBody", 
        value = "登录信息", 
        required = true, 
        dataType = "LoginBodyWithoutCaptcha",
        example = "{\"username\":\"admin\",\"password\":\"admin123\"}"
    )
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class, examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":200,\"msg\":\"操作成功\",\"token\":\"eyJhbGciOiJIUzUxMiJ9.xxx\"}")
        })),
        @ApiResponse(code = 500, message = "用户不存在/密码错误", examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":500,\"msg\":\"用户不存在/密码错误\"")
        }))
    })
    @PostMapping("/loginWithoutCaptcha")
    public AjaxResult loginWithoutCaptcha(@RequestBody LoginBodyWithoutCaptcha loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        
        // 验证学生过期时间
        SysStudent sysStudent = sysStudentMapper.selectByName(loginBody.getUsername());
        if (sysStudent == null) {
			return AjaxResult.error("用户名不存在");
		}
        String today = DateUtil.getYYYY_MM_DD(new Date());
        if (today.compareTo(sysStudent.getExpireTime()) > 0) {
        	return AjaxResult.error("不在有效期范围内");
		}
        
        // 生成令牌，跳过验证码校验
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), "", "");
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    
    @ApiOperation(
        value = "用户登录（无验证码）", 
        notes = "用于系统用户登录认证，仅校验用户名和密码的正确性，不需要验证码",
        response = AjaxResult.class,
        responseReference = "{\"成功\":{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"token\":\"eyJ0eXAi...\"}},\"失败\":{\"code\":500,\"msg\":\"用户不存在/密码错误等具体错误信息\"}}"
    )
    @ApiImplicitParam(
        name = "loginBody", 
        value = "登录信息", 
        required = true, 
        dataType = "LoginBodyWithoutCaptcha",
        example = "{\"username\":\"admin\",\"password\":\"admin123\"}"
    )
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class, examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":200,\"msg\":\"操作成功\",\"token\":\"eyJhbGciOiJIUzUxMiJ9.xxx\"}")
        })),
        @ApiResponse(code = 500, message = "用户不存在/密码错误", examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":500,\"msg\":\"用户不存在/密码错误\"")
        }))
    })
    @PostMapping("/loginManage")
    public AjaxResult loginManage(@RequestBody LoginBodyWithoutCaptcha loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌，跳过验证码校验
        String token = loginService.loginWithoutCaptcha(loginBody.getUsername(), loginBody.getPassword(), loginBody.getIsAutoLogin());
//        		.login(loginBody.getUsername(), loginBody.getPassword(), "", "");
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
